<?php

// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单结算ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */
quanli_require('module/base/bill/billSearch.class.php');

class ajax_financialReconciliation {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && is_numeric($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch ($_REQUEST['operFlg']) {

                case 1:
                    $this->financialReconciliationList();
                    break;

                case 2:
                    $this->financialBatchReconciliation();//财务批量对账
                    break;

                case 100:
                    $this->financialReconciliation();//财务对账
                    break;

                case 101:
                    $this->reconciliationRejected();//配送对账驳回
                    break;

            }
        } else {

            $this->toReturn('参数错误');
        }
    }

    /**
     * 返回信息
     * @param string $message
     * @param int $code
     * @param mixed $data
     */
    private function toReturn($message, $code = 400, $data = '') {

        die(json_encode(array('code' => $code, 'message' => $message, 'data' => $data)));
    }

    /**
     * 查询订单信息
     */
    private function financialReconciliationList() {

        global $G_SHOP;

        //查询条件选择了城市、配送站 则根据选择的城市、配送站查询
        if( isset($_REQUEST['deliver_cityid']) && is_numeric($_REQUEST['deliver_cityid']) && isset( $_REQUEST['distribution_id']) && is_numeric($_REQUEST['distribution_id'])){
            $_REQUEST['deliver_cityid'] = $_REQUEST['deliver_cityid'];
            $_REQUEST['distribution_id'] = $_REQUEST['distribution_id'];

            //查询条件选择了城市、没有选择配送站 则根据选择的城市、当前登录用户权限下的配送站查询
        }else if(isset($_REQUEST['deliver_cityid']) && is_numeric($_REQUEST['deliver_cityid']) && !isset( $_REQUEST['distribution_id']) || !is_numeric($_REQUEST['distribution_id']) ){
            $_REQUEST['deliver_cityid'] = $_REQUEST['deliver_cityid'];
            $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');

            $distribution_id_array = $PS_LOGIN_SESSION['distribution'];//权限下的配送站id数组

            if( count($distribution_id_array) > 1){

                $distribution_id_arg = implode( ',',$distribution_id_array );

                $_REQUEST['extend'] = ' AND distribution_id IN ('.$distribution_id_arg.')';

            }else{
                $_REQUEST['distribution_id'] = $distribution_id_array[0];

            }

            //查询条件没有选择城市、没有选择配送站 则根据选择的城市、当前登录用户权限下的城市、配送站查询
        }else{

            $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');

            $distribution_id_array = $PS_LOGIN_SESSION['distribution'];//权限下的配送站id数组

            if( count($distribution_id_array) > 1){

                $distribution_id_arg = implode( ',',$distribution_id_array );

                $_REQUEST['extend'] = ' AND distribution_id IN ('.$distribution_id_arg.')';

            }else{
                $_REQUEST['distribution_id'] = $distribution_id_array[0];

            }
        }

        //实例订单类
        $billSearch = new billSearch($G_SHOP->DBCA);

//        $_REQUEST['billStatus'] = 7;

        //查询订单信息
        $bill_array = $billSearch->searchSendBill($_REQUEST);

        //组织返回的数据
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );

        if ($bill_array) {

            $edit_permission = $G_SHOP->has_permission(20511);

            foreach ($bill_array as &$bill) {

                //查询订单支付信息
                $arg_array = array(
                    'bill_no' => $bill['bill_no']
                );

                $bill_pay_array = $billSearch->searchBillPay( $arg_array );

                $bill_pay_money_array = $billSearch->searchBillPayMoney( $arg_array );

                $cashReceivable = 0;//应收现金
                $accountsReceivableCreditCard = 0;//应收刷卡
                $paidInCash = 0;//现金回款
                $paidInCreditCard = 0;//刷卡回款
                $notPayInCash = 0;//未回款金额
                $outstandingCreditCard = 0;//未回款刷卡金额

                if($bill['is_reconciliation'] == 1){
                    if($bill_pay_money_array){
                        foreach($bill_pay_money_array as $bill_pay_money){
                            if($bill_pay_money['type'] == 1){
                                if($bill_pay_money['payment_method_type'] == 1){
                                    $cashReceivable += $bill_pay_money['receipt_amount'];//应收现金
                                    $paidInCash += $bill_pay_money['receipt_amount'];//现金回款
                                    $notPayInCash = $cashReceivable - $paidInCash;
                                }
                                if($bill_pay_money['payment_method_type'] == 2 || $bill_pay_money['payment_method_type'] == 3){
                                    $accountsReceivableCreditCard += $bill_pay_money['receipt_amount'];//应收刷卡
                                    $paidInCreditCard += $bill_pay_money['receipt_amount'];//刷卡回款
                                    $outstandingCreditCard = $accountsReceivableCreditCard - $paidInCreditCard;
                                }
                            }
                        }
                    }
                }

                if($bill['is_reconciliation'] == 0){
                    if($bill_pay_array){
                        foreach($bill_pay_array as $bill_pay){
                            if($bill_pay['type'] == 1){
                                if($bill_pay['payment_method_type'] == 1){
                                    $cashReceivable += $bill_pay['receipt_amount'];//应收现金
                                    $paidInCash += $bill_pay['receipt_amount'];//现金回款
                                    $notPayInCash = $cashReceivable - $paidInCash;
                                }
                                if($bill_pay['payment_method_type'] == 2 || $bill_pay['payment_method_type'] == 3){
                                    $accountsReceivableCreditCard += $bill_pay['receipt_amount'];//应收刷卡
                                    $paidInCreditCard += $bill_pay['receipt_amount'];//刷卡回款
                                    $outstandingCreditCard = $accountsReceivableCreditCard - $paidInCreditCard;
                                }
                            }
                        }
                    }
                }

                $operate = "";
                //显示订单对账按钮
                if($bill['is_reconciliation'] == 1 && $bill['is_receivable'] == 0){
                    if($G_SHOP->has_permission(20514)){
                        $operate .= '<span style="border: 1px; border-radius: 4px; width: 70px; height: 30px; padding: 3px 9px; background:#3071a9;"><a  href="javascript: void(0);"onclick="orderSettlement.financial(\'' . $bill['bill_code'] . '\' , \''.$bill['bill_no'].'\');"><font style="color:#fff">财务对账</font></a></span>&nbsp;&nbsp;&nbsp;';
                    }
                    if($G_SHOP->has_permission(20515)){
                        $operate .= '<span style="border: 1px; border-radius: 4px; width: 70px; height: 30px; padding: 3px 9px; background:#3071a9;"><a  href="javascript: void(0);"onclick="orderSettlement.rejected(\'' . $bill['bill_code'] . '\' , \''.$bill['bill_no'].'\');"><font style="color:#fff">驳回</font></a></span>';
                    }
                }else if($bill['is_reconciliation'] == 0 && $bill['is_receivable'] == 0){
                    if($G_SHOP->has_permission(20513)){
                        $operate .= '<span style="border: 1px; border-radius: 4px; width: 70px; height: 30px; padding: 3px 9px; background:#3071a9;"><a  href="javascript: void(0);"onclick="orderSettlement.reconciliation(\'' . $bill['bill_code'] . '\' , \''.$bill['bill_no'].'\');"><font style="color:#fff">配送对账</font></a></span>';
                    }
                }

                //判断配送对账是否完成
                if($bill['is_reconciliation'] == 1){
                    $distributionReconciliation = "已完成";
                }else{
                    $distributionReconciliation = "未完成";
                }

                //判断配送对账是否完成
                if($bill['is_receivable'] == 1){
                     $financialReconciliation = "已完成";
                }else{
                    $financialReconciliation = "未完成";
                }

                if ($edit_permission) {

                    $result_array['rows'][] = array(
                        'id' => $bill['bill_code'],
                        'cell' => array(
                            $operate,
                            $bill['distribution_name'],
                            '<a href="javascript: void(0);" onclick="orderSettlement.billview(\''.$bill['bill_no'].'\');">'.$bill['bill_code'].'</a>',
                            $bill['send_date'],
                            $distributionReconciliation,
                            $financialReconciliation,
                            $bill['distribution_technicia'],
                            $cashReceivable,
                            $accountsReceivableCreditCard,
                            $paidInCash,
                            $paidInCreditCard,
                            $notPayInCash,
                            $outstandingCreditCard
                        )
                    );
                } else {

                    $result_array['rows'][] = array(
                        'id' => $bill['bill_code'],
                        'cell' => array(
                            $bill['distribution_name'],
                            $bill['bill_code'],
                            $bill['send_date'],
                            $distributionReconciliation,
                            $financialReconciliation,
                            $bill['distribution_technicia'],
                            $cashReceivable,
                            $accountsReceivableCreditCard,
                            $paidInCash,
                            $paidInCreditCard,
                            $notPayInCash,
                            $outstandingCreditCard
                        )
                    );
                }
            }
        }

        echo json_encode($result_array);
    }

    /**
     * 财务批量对账
     */
    private function financialBatchReconciliation() {

        global $G_SHOP;

        if (!isset($_REQUEST['financialReconciliation_array']) || !is_array($_REQUEST['financialReconciliation_array']) || empty($_REQUEST['financialReconciliation_array'])) {
            returnJsonData('系统错误', 400);
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            foreach($_REQUEST['financialReconciliation_array'] as &$bill_code) {

                //查询订单状态
                $bill_obj = new entity('bill_master');
                $bill_obj->bill_code = $bill_code;

                if (!$G_SHOP->DBCA->fetch($bill_obj)){
                    throw new Exception( $bill_code.'订单信息没找到' , 404);
                }
                if($bill_obj->bill_status != 7){
                    throw new Exception( $bill_code.'订单没有完成' , 404);
                }
                if($bill_obj->is_reconciliation == 0){
                    throw new Exception( $bill_code.'订单配送对账没有完成' , 404);
                }
                if($bill_obj->is_receivable == 1){
                    throw new Exception( $bill_code.'订单财务对账已完成' , 404);
                }
                //改变订单状态
                $bill_obj->is_receivable = 1;
                //保存订单状态
                $G_SHOP->DBCA->save( $bill_obj ) ;

            }

            $G_SHOP->DBCA->commit();

            returnJsonData( 'ok',200 );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                returnJsonData( $e->getMessage() , $e->getCode() );
            } else {
                error_log($e->getMessage());
                returnJsonData( '系统错误', 500 );
            }

        }

    }

    /**
     * 订单财务对账
     */
    private function financialReconciliation() {

        global $G_SHOP;


        if (!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no'])) {
            returnJsonData('系统错误', 400);
        }

        try{
            //检查订单是否存在
            $bill_obj = new entity('bill_master');
            $bill_obj->bill_no = $_REQUEST['bill_no'] ;
            if (!$G_SHOP->DBCA->fetch( $bill_obj ))
                throw new Exception( "订单信息没找到，请刷新页面重试" , 404);

            //检查配送对账是否完成
            if($bill_obj->is_reconciliation == 0){
                throw new Exception( '订单配送对账没有完成' , 404);
            }

            //检查财务已经对账
            if($bill_obj->is_receivable ==  1){
                throw new Exception( "订单已对账，请刷新页面" , 404);
            }

            //更新对账字段
            $bill_obj->is_receivable = 1;

            $G_SHOP->DBCA->save( $bill_obj , 'bill_master' );

            returnJsonData( '财务对账成功', 200 );

        }catch (Exception $e) {
            if ($e->getCode() > 0)
                returnJsonData( $e->getMessage(), $e->getCode() );
            else {
                error_log($e->getMessage());
                returnJsonData( '系统错误', 500 );
            }
        }

    }

    /**
     * 驳回配送对账
     */
    public function reconciliationRejected(){

        global $G_SHOP;

        if(isset($_REQUEST['bill_no']) && empty($_REQUEST['bill_no'])){
            returnJsonData( "参数错误", 400 );
        }

        quanli_include('module/base/common/quanliLog.class.php');

        //实例日志类
        $quanliLog = new quanliLog();

        try{

            //检查订单是否存在
            $bill_obj = new entity('bill_master');
            $bill_obj->bill_no = $_REQUEST['bill_no'] ;
            if (!$G_SHOP->DBCA->fetch( $bill_obj ))
                throw new Exception( "订单信息没找到，请刷新页面重试" , 404);

            //检查订单配送对账是否完成
            if($bill_obj->is_reconciliation == 0){
                throw new Exception( "订单配送对账未完成，不能执行驳回操作" , 404);
            }
            //检查订单财务对账是否完成
            if($bill_obj->is_receivable == 1){
                throw new Exception( "订单财务对账已完成，不能执行驳回操作" , 404);
            }

            //删除配送对账表信息
            $delete_sql = 'DELETE FROM  bill_distribution_checking WHERE bill_no = ? ';
            $G_SHOP->DBCA->stmt_query($delete_sql, 's', $_REQUEST['bill_no']);

            //删除保存已对账完成订单bill_finish表信息
            $delete_sql = 'DELETE FROM  bill_finish WHERE bill_no = ? ';
            $G_SHOP->DBCA->stmt_query($delete_sql, 's', $_REQUEST['bill_no']);

            //检索订单结算临时表
            $bill_temp_obj = new entity('bill_distribution_temp');
            $bill_temp_obj->bill_no = $_REQUEST['bill_no'];
            if (!$G_SHOP->DBCA->fetch($bill_temp_obj)){
//                returnJsonData( '订单临时信息没找到', 404 );
                //更新配送对账信息字段
                $bill_obj->bill_status = 6;
                $bill_obj->is_reconciliation = 0;
                $bill_obj->bill_checking_remark = "";
                $bill_obj->bill_reject_cause = $_REQUEST['bill_reject_cause'];

            }else{

                //更新配送对账信息字段
                $bill_obj->bill_status = $bill_temp_obj->bill_status;
                $bill_obj->bill_receivable_money = $bill_temp_obj->bill_receivable_money;
                $bill_obj->bill_received_money = $bill_temp_obj->bill_received_money;
                $bill_obj->is_reconciliation = 0;
                $bill_obj->bill_checking_remark = "";
                $bill_obj->bill_reject_cause = $_REQUEST['bill_reject_cause'];
            }

            $G_SHOP->DBCA->save( $bill_obj );

            //删除订单结算临时表信息
            $delete_sql = 'DELETE FROM  bill_distribution_temp WHERE bill_no = ? ';
            $G_SHOP->DBCA->stmt_query($delete_sql, 's', $_REQUEST['bill_no']);

            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $_REQUEST['bill_no'],
                'extend_1' => '配送对账驳回',
                'extend_2' => $bill_obj->bill_reject_cause == "" ? '已驳回' : '因'.$bill_obj->bill_reject_cause.'已驳回',
                'extend_5' => 7,
                'operator' => $G_SHOP->currentUserName
            );

            $quanliLog->saveLogInfo( $log_array );

            returnJsonData( '驳回成功', 200 );

        }catch (Exception $e) {
            if ($e->getCode() > 0)
                returnJsonData( $e->getMessage() ,$e->getCode() );
            else {
                error_log($e->getMessage());
                returnJsonData( '系统错误', 500 );
            }
        }
    }

}
